package org.chenbingkang.other;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.google.common.base.CaseFormat;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Application {


    public static String COOKIE = "NX-ANTI-CSRF-TOKEN=dd471229-8b78-4fd2-9c33-366dd1d0b6d4; NEXUS_CAS=https://icmsauthn.service.rd/logout?service=https://icosrepos.service.rd/; JSESSIONID=node01oitp97gtm2ac1l2ni06cuskyh12.node0; NXSESSIONID=aefadc73-89d8-42e5-b43b-4ad18bc28ac6";


    private static DateTimeFormatter UTC_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

    public static String getCurrentTimeStr() {
        ZonedDateTime localDateTime = ZonedDateTime.now();
        return localDateTime.format(UTC_FORMAT);
    }

    public static void main(String... args) throws Exception {
        Connection connection = DriverManager.getConnection("jdbc:mysql://9.135.231.50:3306/traffic_maas", "root", "Tencent123!");
        Statement statement = connection.createStatement();
        ResultSet rs = statement.executeQuery("select * from appoint_info");
        ResultSetMetaData rsmd = rs.getMetaData();
        Map<String, Object> map = new LinkedHashMap<>();
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {

            String field = rsmd.getColumnName(i);
            field=CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, field);
            int type = rsmd.getColumnType(i);
            if (Arrays.asList(-7, -6, 4, 5, -5, 6, 7, 8, 2, 3).contains(type)) {
                map.put(field, 0);
            } else {
                map.put(field, " ");
            }
        }
        System.out.println(JSON.toJSONString(map));
    }

    public static void func(String localPath, String parentUrl, List<String> dirs) throws Exception {
        System.out.println("==============" + parentUrl);
        for (String s : dirs) {
            if (s.contains("https")) {
                downloadFile(s, localPath + s.substring(s.lastIndexOf("/") + 1));
            } else {
                OkHttpClient okHttpClient = new OkHttpClient();
                okHttpClient.setReadTimeout(10, TimeUnit.SECONDS);
                Request request = new Request.Builder()
                        .url(parentUrl + s)
                        .addHeader("Cookie", COOKIE)
                        .get()//默认就是GET请求，可以不写
                        .build();
                Response response = okHttpClient.newCall(request).execute();
                if (!response.isSuccessful()) {
                    throw new IllegalStateException("");
                }
                File file = new File(localPath + s);
                if (!file.exists()) {
                    file.mkdir();
                }
                List<String> tmpDirs = getDirs(response.body().string());
                func(localPath + s + "/", parentUrl + s + "/", tmpDirs);
            }
        }
    }

    public static List<String> func1(String url) throws Exception {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Cookie", COOKIE)
                .get()//默认就是GET请求，可以不写
                .build();
        Response response = okHttpClient.newCall(request).execute();
        List<String> dirs = getDirs(response.body().string());
        return dirs;
    }

    public static List<String> getDirs(String text) {
        List<String> dirs = new ArrayList<>();
        String pattern = "<a href=\"(.*)\">(.*)</a>";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(text);
        for (int j = 0; j < 10000; j++) {
            if (m.find()) {
                String s1 = m.group(1);
                String s2 = m.group(2);
                if (s1.contains("https")) {
                    dirs.add(s1);
                } else if (!s2.contains("Parent Directory")) {
                    dirs.add(s2);
                }
            } else {
                break;
            }
        }
        return dirs;
    }

    public static void downloadFile(String url, String filePath) throws Exception {
        if (Files.exists(Paths.get(filePath))) {
            return;
        }

        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Cookie", COOKIE)
                .get()//默认就是GET请求，可以不写
                .build();
        Response response = okHttpClient.newCall(request).execute();
        if (!response.isSuccessful()) {
            throw new IllegalStateException("");
        }
//        Files.createFile(Paths.get(filePath));
        Files.write(Paths.get(filePath), response.body().bytes());
    }
}
